package com.labor_management_system.Controller;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.labor_management_system.Entity.Employee;
import com.labor_management_system.Entity.Enterprises;
import com.labor_management_system.Entity.Team;
import com.labor_management_system.Service.EmployeeService;
import com.labor_management_system.Service.EnterprisesService;
import com.labor_management_system.Service.TeamService;
import com.labor_management_system.Utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@RestController
@CrossOrigin
public class WorkerRosterController {
    //工人名册管理
    @Autowired
    EmployeeService employeeService;
    @Autowired
    TeamService teamService;
    @Autowired
    EnterprisesService enterprisesService;
    @PostMapping("/TEST/Gen2")
    public R gen2(){
        Random random = new Random();

        for (int i = 0; i < 50; i++) {
            Employee employee = new Employee();
            employee.setEmployeeId(UUID.randomUUID().toString());
            employee.setEmployeeName("Employee " + i);
            employee.setTeamId("59d78de6-328b-4266-950b-2103eb1f1dfc"); // 替换为实际的 team_id
            employee.setEnterprisesId("7cef5d9e-a8d6-4321-aac6-f02b9532190c"); // 替换为实际的 enterprises_id
            employee.setSex(random.nextBoolean() ? "M" : "F"); // 随机设置性别
            employee.setIdentityCard(generateRandomIdentityCard()); // 随机生成身份证号码
            employee.setAge(random.nextInt(50) + 18); // 随机生成 18 到 67 之间的年龄
            employee.setRemunerationMethod(random.nextInt(3) + 1); // 随机生成 1 到 3 之间的薪酬方式
            employee.setPhone("138" + String.format("%08d", random.nextInt(100000000))); // 随机生成 11 位手机号
            employee.setWageScale(random.nextInt(10) + 1); // 随机生成 1 到 10 之间的工资等级
            employee.setPayrollCard("Payroll Card " + i);
            employee.setBank("Bank " + i);
            employee.setAttendanceDaysCmonth(random.nextInt(31) + 1); // 随机生成 1 到 31 之间的出勤天数
            employee.setSalaryPayableTmonth(random.nextInt(10000) + 1000); // 随机生成 1000 到 11000 之间的应发工资
            employeeService.getBaseMapper().insert(employee);
        }
        return R.ok();
    }
    private static String generateRandomIdentityCard() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        // 生成前17位数字
        for (int i = 0; i < 17; i++) {
            sb.append(random.nextInt(10));
        }

        // 生成校验位
        int[] factors = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        char[] checkCodes = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        int sum = 0;

        for (int i = 0; i < sb.length(); i++) {
            sum += (sb.charAt(i) - '0') * factors[i];
        }

        int remainder = sum % 11;
        sb.append(checkCodes[remainder]);

        return sb.toString();
    }

    @GetMapping("GET/PreCreateEmployee")
    public R preCreateEmployee(){
        //返回班组和单位信息
        return R.ok().data("ProjectNameAndID",new JSONArray(teamService.getTeamIDAndName()))
                .data("EnterprisesNameAndID",new JSONArray(enterprisesService.getEnterprisesIDAndName()));
    }
    @PostMapping("POST/CreateEmployee")
    public R createEmployee(@RequestBody Employee employee){//记得写班组size增长
        employee.setEmployeeId(UUID.randomUUID().toString().replace("-",""));
        return employeeService.getBaseMapper().insert(employee)>0?(teamService.getBaseMapper().update(null, new UpdateWrapper<Team>().eq("team_id", employee.getTeamId()).setSql("team_size = team_size + 1"))>0?R.ok():R.error()):R.error();
    }
    @PostMapping("POST/UpdateEmployee")
    public R updateEmployee(@RequestBody Employee employee){
        return employeeService.getBaseMapper().updateById(employee)>0?R.ok():R.error();

    }
    @PostMapping("/POST/DeleteEmployee")//记得写班组size减小
    public R deleteEmployeeByID(@RequestParam(value="employeeId")String employeeId){
        teamService.getBaseMapper().update(null, new UpdateWrapper<Team>().eq("team_id",employeeService.getBaseMapper().selectOne(new QueryWrapper<Employee>().eq("employee_id",employeeId)).getTeamId()).setSql("team_size = team_size - 1"));
        return employeeService.getBaseMapper().deleteById(employeeId)>0?R.ok():R.error();
    }
    @PostMapping("/GET/GetEmployeeInfo")
    public R getEmployeeInfo(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize){
        return R.ok().data("pageData",new JSONArray(employeeService.getBaseMapper()
                                                    .selectPage(new Page<>(pageNum,pageSize),null)
                                                    .getRecords()));
    }
    @PostMapping("/GET/GetEmployeeInfoByTeamName")
    public R getEmployeeInfoByTeamName(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,@RequestParam("teamName") String teamName){
        return R.ok().data("pageData",new JSONArray( employeeService.getBaseMapper().selectList(new LambdaQueryWrapper<Employee>()
                .in(Employee::getTeamId, teamService.getBaseMapper()
                        .selectPage(new Page<>(pageNum,pageSize),new QueryWrapper<Team>().like("team_name", teamName)).getRecords()
                        .stream().map(Team::getTeamId).collect(Collectors.toList())))));
    }
    @PostMapping("/GET/GetEmployeeInfoByEmployeeName")
    public R getEmployeeInfoByEmployeeName(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,@RequestParam("employeeName") String employeeName){
        return R.ok().data("pageData",new JSONArray(employeeService.getBaseMapper()
                .selectPage(new Page<>(pageNum,pageSize),new QueryWrapper<Employee>()
                        .eq("employee_name",employeeName))
                .getRecords()));
    }



}
